<?php
require 'item.php';
class Collection extends Item
{
	var $rdf_type;
	var $limit = 20;
	var $offset = 0;
	var $filter = '';
	var $object = false;
	var $filter_required = false;
	var $filter_predicates = array();
	var $order_predicate=false;
	var $sort_order=false;
	
	function GET()
	{	
		$rdf = $this->namespaces['rdf'];
		$rdfs = $this->namespaces['rdfs'];
		$dc = $this->namespaces['dc'];
		
		$object_clause = '';
		if(is_array($this->object))
		{
			$object = ($this->object['type']=='uri')? 
				"<{$this->object['value']}>" : '"""'.$this->object['value'].'"""';
			$object .= (!empty($this->object['lang']))? '@'.$this->object['lang'] : '';
			$object_clause = "?list_item ?property {$object} . ";
		}
		
		/* get rdf:type clauses */
		$type_clauses = $this->get_type_clauses($this->rdf_type);
		$type_constraints = (!empty($type_clauses))? implode(' UNION ', $type_clauses) : '';
		/* get filter */
		
		$filter = $this->get_filter_clause();
				
		
		/* get limit and offset */
		if(isset($_GET['limit'])) $this->limit = $_GET['limit'];
		if(isset($_GET['offset'])) $this->offset = $_GET['offset'];
		
		$clause = (isset($this->clause))? $this->clause : "{$object_clause} \n {$type_constraints} ";
		
		$query = <<<_SPARQL_
	DESCRIBE ?list_item 
	 WHERE { 
				{$clause}
				{$filter}
			}  
	LIMIT {$this->limit} OFFSET {$this->offset}
_SPARQL_;
		
		$this->variables['query'] = $query;
		if(!isset($_GET['sparql']) and (!$this->filter_required or !empty($this->filter)) )
		{
			$response = $this->store->sparql_service->graph($query);
			$this->variables['rdf_xml'] = $response->body;
			$this->variables['resources'] = $this->Convert->RDFXML->to_resources($this->variables['rdf_xml'])->value();
		}
		else if(isset($_GET['sparql']))
		{
			$query = urlencode($this->variables['query']);
			header("Location: /services/sparql?query={$query}");
			exit;
		}
		return $this->show();
	}
	
	function get_type_clauses($types)
	{
		if($types===false) return array('');
		else if(empty($types)) return(array());
		
		if(!is_array($types)) $types = array($types);
		
		$type_clauses = array();		
		
		foreach($types as $type)
		{
			$type_clauses[]= '{ ?list_item a <'.$type.'> }';
		}
		
		return $type_clauses;
	}
	
	function get_filter_clause()
	{
		$rdfs = $this->namespaces['rdfs'];
		$dc = $this->namespaces['dc'];
		
		if(isset($_GET['q'])) $this->filter = $_GET['q'];
		
		if($this->filter)
		{
			
			if(is_string($this->filter_predicates)) $this->filter_predicates = array($this->filter_predicates);
			
			$predicate_clauses = array();
			
			if(empty($this->filter_predicates))
			{
				$predicate_clauses = array(' ?list_item ?p ?o . ');
			}
			else
			{
				foreach($this->filter_predicates as $p) $predicate_clauses[]='{ ?list_item <'.$p.'> ?o }'."\r\n";
			}
			
		
			
			return implode(' UNION ', $predicate_clauses)."\r\n".' FILTER(isLiteral(?o)) . FILTER(REGEX(STR(?o), \''.addslashes($this->filter).'\',"i")) ';
		}
		else
			return '';
	}
	
}

?>